package myJs

import myJs.Utils._
import myJs.Implicits._
import myJs.myPkg.{ColumnOptions, Swal, SwalOptions, TableOptions}
import scalatags.Text.all._

import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import myJs.myPkg.bootstrap.Bootstrap.default._
import Tool._
import myJs.myPkg.jquery._

import scala.collection.immutable.SeqMap
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSConverters._

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("UserManage")
object UserManage {

  @JSExport("init")
  def init = {
    initTable
    refreshUser()

  }

  def tbFmt(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[js.Any]) => columnName match {
    case _ => v
  }

  def expStyle(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[Any]) => columnName match {
    case _ => v
  }

  val operateColumn = js.Array(
    ColumnOptions.field("operate").title("操作").formatter(operateFmt).filterControl("clear")
  )

  def initTable = {
    val map = SeqMap("name" -> "用户名", "unit" -> "所属单位","createTime"->"创建时间")
    val columnNames = map.keyList
    val columns = columnNames.map { columnName =>
      val title = map.getOrElse(columnName, columnName)
      val fmt = tbFmt(columnName)
      val style = expStyle(columnName)
      val basicOptions = ColumnOptions.field(columnName).title(title).sortable(true).formatter(fmt).cellStyle(style)
      columnName match {
        case x if List().contains(x) => basicOptions.
          sortable(false).operateable(true)
        case _ => basicOptions
      }
    }.concat(operateColumn)
    val options = TableOptions.columns(columns.toJSArray).searchOnButton(false).filterControl(false)
    $(s"#table").bootstrapTable(options)
  }

  @JSExport("refreshUser")
  def refreshUser(f: () => js.Any = () => ()) = {
    val url = g.jsRoutes.controllers.AdminController.getAllUser().url.toString
    val ajaxSettings = JQueryAjaxSettings.url(s"${url}?").contentType("application/json").
      `type`("get").success { (data, status, e) =>
      $("#table").bootstrapTable("load", data)
      f()
    }
    $.ajax(ajaxSettings)

  }

  def operateFmt: js.Function = {
    (v: js.Any, row: js.Dictionary[js.Any]) =>
      val resetStr = a(
        title := "重置",
        onclick := s"UserManage.resetShow('" + row("id") + "')",
        cursor.pointer,
        span(
          em(cls := "fa fa-repeat")
        )
      )
      val deleteStr = a(
        title := "删除",
        cursor.pointer,
        onclick := s"deleteData('" + row("id") + "')",
        target := "_blank",
        span(
          em(cls := "fa fa-close")
        )
      )
      Array(resetStr, deleteStr).mkString("&nbsp;")
  }

  @JSExport("resetShow")
  def resetShow(id: String) = {
    val formId="updateForm"
    val url = g.jsRoutes.controllers.AdminController.getUserById().url.toString
    val ajaxSettings = JQueryAjaxSettings.url(s"${url}?id=${id}").
      `type`("get").success { (data, status, e) =>
      val rs = data.asInstanceOf[js.Dictionary[String]]
      fillByNames(rs,formId)
      jQuery("#updateModal").modal("show")
    }
    $.ajax(ajaxSettings)
  }

  @JSExport("update")
  def update = {
    val formId = "updateForm"
    val bv = jQuery(s"#${formId}").data("bootstrapValidator")
    bv.validate()
    val valid = bv.isValid().asInstanceOf[Boolean]
    if (valid) {
      val data = $(s"#${formId}").serialize()
      val index = layer.alert(myElement, layerOptions)
      val url = g.jsRoutes.controllers.AdminController.updateUser().url.toString
      val ajaxSettings = JQueryAjaxSettings.url(url).`type`("post").data(data).success { (data, status, e) =>
        refreshUser { () =>
          layer.close(index)
          jQuery("#updateModal").modal("hide")
          bv.resetForm(true)
          Swal.swal(SwalOptions.title("成功").text("密码重置成功!").`type`("success"))
        }

      }
      $.ajax(ajaxSettings)
    }
  }


}
